//
//  MTTabBar.swift
//  MTWeiBo
//
//  Created by user on 2017/7/22.
//  Copyright © 2017年 itcast. All rights reserved.
//

import UIKit

//定义代理协议
protocol MTTabBarDelegate: NSObjectProtocol {
    //定义代理方法
    func clickComposeButtonOperation()
}


//自定义tabbar
class MTTabBar: UITabBar {

    //定义闭包属性
    var composeButtenClosure: (()->())?
    //定义代理
    var mtTabbarDelegate: MTTabBarDelegate?
    //懒加载控件
    private lazy var composeButten = { () -> UIButton in 
        let butten = UIButton()
        //添加点击事件
        butten.addTarget(self, action: #selector(composeButtenAction), for: .touchUpInside)
        //设置不同状态下的背景图片
        butten.setBackgroundImage(UIImage(named: "tabbar_compose_button"), for: .normal)
        butten.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), for: .highlighted)
        //设置不同状态下的图片
        butten.setImage(UIImage(named: "tabbar_compose_icon_add"), for: .normal)
        butten.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), for: .highlighted)
        //大小
        butten.sizeToFit()
        
        return butten
        
    }()
    
    //手写代码创建对象
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        //fatalError("init(coder:) has not been implemented")
        //支持xib
        super.init(coder: aDecoder)
        setupUI()
    }
    
    
    func setupUI() {
        //解决阴影bug
        backgroundImage = UIImage(named: "tabbar_background")
        addSubview(composeButten)
    }
    
    
    //按钮点击事件
    @objc private func composeButtenAction() {
        
        //判断闭包是否优质
        composeButtenClosure?()
        //使用代理对象调用方法
        mtTabbarDelegate?.clickComposeButtonOperation()
    }
    
    //重写布局
    override func layoutSubviews() {
        super.layoutSubviews()
        
        //设置中心点
        composeButten.centerX = width * 0.5
        composeButten.centerY = height * 0.5
        
        //计算每项按钮的宽度
        let buttenWidth = width / 5
        //记录缩影
        var index = 0
        
        
        for subView in subviews{
            
            //判断是否是系统指定的按钮
            if subView.isKind(of: NSClassFromString("UITabBarButton")!){
                subView.width = buttenWidth
                subView.x = buttenWidth * CGFloat(index)
                index += 1
                if(index == 2){
                    index = 3
                }
                
            }
        }
        
        
    }
    
    
}
